<template>
  <div class="wechat">
    <!-- 卡片视图区域 -->
    <div class="wechat_card">
      <!-- 布局 -->
      <el-row :gutter="20" class="wechat_card_head" type="flex">
        <el-col :span="8">
          <!-- 搜索框及添加区域 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getComAdviceList" size="medium">
            <el-button slot="append" size="medium" icon="el-icon-search" @click="getComAdviceList"></el-button>
          </el-input>
        </el-col>
        <el-button size="medium" class="btn_head_medium" type="primary" @click="addDialogVisible = true" icon="el-icon-circle-plus-outline">新增</el-button>

        <el-button size="medium" type="danger" @click="removeUserByIds" icon="el-icon-remove-outline">删除</el-button>
        <!-- 表格列筛选 -->
        <div class="tools_head">
          <el-popover placement="bottom" trigger="click">
            <el-checkbox-group v-model="colOptions">
              <el-checkbox v-for="item in colSelect" :label="item" :key="item" style="display: block; margin: 10px">
              </el-checkbox>
            </el-checkbox-group>
            <div slot="reference">
              <el-tooltip content="筛选列" placement="bottom">
                <el-button size="small" icon="el-icon-menu"></el-button>
              </el-tooltip>
            </div>
            <el-button size="small" type="text" @click="filterFunHandle('allchecked')">全选</el-button>
            <el-button size="small" type="text" @click="filterFunHandle('cancel')">取消全选</el-button>
          </el-popover>
          <el-tooltip content="导出excel" placement="bottom">
            <el-button size="small" icon="el-icon-download" style="margin-left: 10px" @click="handleDownload"></el-button>
          </el-tooltip>
        </div>
      </el-row>
      <!-- 投诉建议列表区域 -->
      <el-table :data="complainAdviceList" style="width: 100%" border stripe :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }" ref="tableDataRef" height="85%" size="small" :row-key="
          (row) => {
            return row.id;
          }
        " @selection-change="handleSelectionChange">
        <el-table-column type="selection" :reserve-selection="true"></el-table-column>
        <el-table-column type="index" label="序号" v-if="colData[0].istrue"></el-table-column>
        <el-table-column prop="roomNo" label="房间号" v-if="colData[1].istrue"></el-table-column>
        <el-table-column prop="floorName" label="楼栋号" v-if="colData[2].istrue"></el-table-column>
        <el-table-column prop="floorUnitName" label="单元号" v-if="colData[3].istrue"></el-table-column>
        <el-table-column prop="name" label="投诉人姓名" v-if="colData[4].istrue" width="100px"></el-table-column>
        <el-table-column prop="phone" label="投诉人电话" v-if="colData[5].istrue" width="130px"></el-table-column>
        <el-table-column prop="complaintTime" label="投诉时间" v-if="colData[6].istrue" width="180px">
        </el-table-column>
        <el-table-column prop="itemName" label="投诉事项" v-if="colData[7].istrue"></el-table-column>
        <el-table-column prop="content" label="投诉/建议内容" v-if="colData[8].istrue" show-overflow-tooltip width="150px"></el-table-column>
        <el-table-column prop="effective" label="有效性" v-if="colData[9].istrue">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.effective === 0" type="success">待判断</el-tag>
            <el-tag v-else-if="scope.row.effective === 1" type="danger">无效</el-tag>
            <el-tag v-else type="warning">有效</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="employeeName" label="处理人员" v-if="colData[10].istrue"></el-table-column>
        <el-table-column prop="state" label="处理状态" v-if="colData[11].istrue" width="100px" :filters="[
            { text: '未处理', value: 0 },
            { text: '已完成', value: 1 },
          ]" :filter-method="filterTag" filter-placement="bottom-end">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.state === 0" type="success">未处理</el-tag>
            <el-tag v-else type="warning">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dealTime" label="处理时间" v-if="colData[12].istrue" width="180px">
        </el-table-column>
        <el-table-column prop="checkTime" label="回访时间" v-if="colData[13].istrue" width="180px">
        </el-table-column>
        <el-table-column prop="checkContent" label="回访内容" v-if="colData[14].istrue"></el-table-column>
        <el-table-column prop="checkResult" label="回访结果" v-if="colData[15].istrue"></el-table-column>
        <el-table-column prop="addUserId" label="添加人" v-if="colData[16].istrue"></el-table-column>
        <el-table-column prop="addTime" label="添加时间" v-if="colData[17].istrue" width="180px">
        </el-table-column>
        <el-table-column prop="memo" label="备注" v-if="colData[18].istrue" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="150px" fixed="right">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加投诉建议的对话框 -->
      <el-dialog title="添加投诉建议信息" :visible.sync="addDialogVisible" width="50%" @close="addDialogReset">
        <!-- 内容主题区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" :inline="true">
          <el-form-item label="房间id" prop="roomId">
            <el-input v-model="addForm.roomId"></el-input>
          </el-form-item>
          <el-form-item label="投诉人姓名" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="投诉人电话" prop="phone">
            <el-input v-model="addForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="投诉时间" prop="complaintTime">
            <el-date-picker v-model="addForm.complaintTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="投诉事项" prop="complianEventId">
            <el-select v-model="addForm.complianEventId" placeholder="请选择投诉事项" class="select">
              <el-option v-for="item in itemList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input v-model="addForm.content"></el-input>
          </el-form-item>
          <el-form-item label="有效性" prop="effective">
            <el-select v-model="addForm.effective" placeholder="请选择有效性" class="select">
              <el-option v-for="item in effectiveList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处理人员" prop="employeeId">
            <el-select v-model="addForm.employeeId" placeholder="请选择处理人员" class="select">
              <el-option v-for="item in employeeList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态" prop="state">
            <el-select v-model="addForm.state" placeholder="请选择处理状态" class="select">
              <el-option v-for="item in statusList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处理时间" prop="dealTime">
            <el-date-picker v-model="addForm.dealTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="回访时间" prop="checkTime">
            <el-date-picker v-model="addForm.checkTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="回访内容" prop="checkContent">
            <el-input v-model="addForm.checkContent"></el-input>
          </el-form-item>
          <el-form-item label="回访结果" prop="checkResult">
            <el-input v-model="addForm.checkResult"></el-input>
          </el-form-item>
          <el-form-item label="小区id" prop="communityId">
            <el-input v-model="addForm.communityId"></el-input>
          </el-form-item>

          <el-form-item label="备注" prop="memo">
            <el-input v-model="addForm.memo"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="add">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改投诉建议信息的对话框 -->
      <el-dialog title="修改投诉建议信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form ref="editFormRef" :model="editForm" label-width="100px" :rules="editFormules" :inline="true">
          <el-form-item label="房间id" prop="roomId">
            <el-input v-model="editForm.roomId"></el-input>
          </el-form-item>
          <el-form-item label="投诉人姓名" prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="投诉人电话" prop="phone">
            <el-input v-model="editForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="投诉时间" prop="complaintTime">
            <el-date-picker v-model="editForm.complaintTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="投诉事项" prop="complianEventId">
            <el-select v-model="editForm.complianEventId" placeholder="请选择投诉事项" class="select">
              <el-option v-for="item in itemList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input v-model="editForm.content"></el-input>
          </el-form-item>
          <el-form-item label="有效性" prop="effective">
            <el-select v-model="editForm.effective" placeholder="请选择有效性" class="select">
              <el-option v-for="item in effectiveList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处理人员" prop="employeeId">
            <el-select v-model="editForm.employeeId" placeholder="请选择处理人员" class="select">
              <el-option v-for="item in employeeList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态" prop="state">
            <el-select v-model="editForm.state" placeholder="请选择处理状态" class="select">
              <el-option v-for="item in statusList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处理时间" prop="dealTime">
            <el-date-picker v-model="editForm.dealTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="回访时间" prop="checkTime">
            <el-date-picker v-model="editForm.checkTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="回访内容" prop="checkContent">
            <el-input v-model="editForm.checkContent"></el-input>
          </el-form-item>
          <el-form-item label="回访结果" prop="checkResult">
            <el-input v-model="editForm.checkResult"></el-input>
          </el-form-item>
          <el-form-item label="小区id" prop="communityId">
            <el-input v-model="editForm.communityId"></el-input>
          </el-form-item>

          <el-form-item label="备注" prop="memo">
            <el-input v-model="editForm.memo"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="edit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="this.queryInfo.pageNum" :page-sizes="[3, 5, 10, 15]" :page-size="this.queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data() {
    // 验证手机号
    var checkMobile = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|19[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的手机
        return callback()
      }
      callback(new Error('请输入合法的手机'))
    }
    return {
      // 获取投诉建议列表的参数对象
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 3
      },
      complainAdviceList: [],
      employeeList: [],
      itemList: [],
      effectiveList: [
        { id: 0, value: '待判断' },
        { id: 1, value: '无效' },
        { id: 2, value: '有效' }
      ],
      statusList: [
        { id: 0, value: '未处理' },
        { id: 1, value: '已完成' },
      ],
      colData: [
        { title: "序号", istrue: true },
        { title: "房间号", istrue: true },
        { title: "楼栋号", istrue: true },
        { title: "单元号", istrue: true },
        { title: "投诉人姓名", istrue: true },
        { title: "投诉人电话", istrue: true },
        { title: "投诉时间", istrue: true },
        { title: "投诉事项", istrue: true },
        { title: "投诉/建议内容", istrue: true },
        { title: "有效性", istrue: true },
        { title: "投诉处理人员", istrue: true },
        { title: "投诉处理状态", istrue: true },
        { title: "投诉处理时间", istrue: true },
        { title: "回访时间", istrue: true },
        { title: "回访内容", istrue: true },
        { title: "回访结果", istrue: true },
        { title: "添加人", istrue: true },
        { title: "添加时间", istrue: true },
        { title: "备注", istrue: true },
      ],
      colOptions: [],//多选框默认全选
      colSelect: [],//所有表头标题,跟多选框组绑定的
      //选中行的id数组
      multipleSelection: [],
      idsArray: {
        ids: []
      },
      total: 0,
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      // 添加投诉建议的表单数据
      addForm: {
        roomId: '',
        risidentId: '',
        name: '',
        phone: '',
        complaintTime: '',
        complianEventId: '',
        content: '',
        effective: '',
        employeeId: '',
        state: '',
        dealTime: '',
        checkTime: '',
        checkContent: '',
        checkResult: '',
        communityId: '',
        addUserId: '',
        addTime: '',
        memo: ''
      },
      // 查询到的编辑投诉建议信息
      editForm: {},
      // 添加表单的验证规则对象
      addFormRules: {
        roomId: [{ required: true, message: '请输入房间id', trigger: 'blur' }],
        name: [{ required: true, message: '请输入投诉人姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入投诉人电话', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur' }],
        complaintTime: [{ required: true, message: '请输入投诉时间', trigger: 'blur' }],
        complianEventId: [{ required: true, message: '请输入投诉事项', trigger: 'blur' }],
        state: [{ required: true, message: '请输入处理状态', trigger: 'blur' }],
        communityId: [{ required: true, message: '请输入小区id', trigger: 'blur' }],

      },
      // 修改投诉建议信息表单的验证规则
      editFormules: {
        roomId: [{ required: true, message: '请输入房间id', trigger: 'blur' }],
        name: [{ required: true, message: '请输入投诉人姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入投诉人电话', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur' }],
        complaintTime: [{ required: true, message: '请输入投诉时间', trigger: 'blur' }],
        complianEventId: [{ required: true, message: '请输入投诉事项', trigger: 'blur' }],
        state: [{ required: true, message: '请输入处理状态', trigger: 'blur' }],
        communityId: [{ required: true, message: '请输入小区id', trigger: 'blur' }],
      }

    }

  },
  created() {
    this.getComAdviceList()
    var _this = this;
    for (let i = 0; i < _this.colData.length; i++) {
      _this.colSelect.push(_this.colData[i].title);
      if (_this.colData[i].title == '添加人' || _this.colData[i].title == '添加时间' || _this.colData[i].title == '回访时间') { //初始化不想展示的列可以放在这个条件里
        continue;
      }
      _this.colOptions.push(_this.colData[i].title);
    }
  },
  watch: {
    // 单选列实现
    colOptions(valArr) {
      var arr = this.colSelect.filter(i => valArr.indexOf(i) < 0); // 未选中
      this.colData.filter(i => {
        if (arr.indexOf(i.title) != -1) {
          i.istrue = false;
        } else {
          i.istrue = true;
        }
      });
      this.$nextTick(() => {
        this.$refs.tableDataRef.doLayout();
      });
    }
  },
  methods: {
    // 获取投诉建议档案列表
    async getComAdviceList() {
      if (this.queryInfo.query !== '')
        //模糊查楼栋号
        this.queryInfo.condition = `name like "%${this.queryInfo.query}%"`
      const { data: res } = await this.$http.get('ComplaintinfoAction/getBasicInfos', { params: this.queryInfo })
      if (!res.success) return this.$message.error('获取投诉建议失败')
      console.log(res)
      this.complainAdviceList = res.rows
      this.total = res.total
      const { data: res1 } = await this.$http.get('ComplianeventAction/getBasicInfos')
      this.itemList = res1.rows
      const { data: res2 } = await this.$http.get('EmployeeinfoAction/getBasicInfos')
      this.employeeList = res2.rows

    },
    //点击按钮
    add() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        //给隐藏的input输入框中的添加人addUserId赋值
        this.addForm.addUserId = window.sessionStorage.getItem('userId')
        // 添加时间
        this.addForm.addTime = this.dateFormat()
        //console.log(this.addForm.addTime)
        const { data: res } = await this.$http.post("ComplaintinfoAction/addObject", this.addForm)
        if (!res.success) return this.$message.error('添加投诉建议失败')
        //关闭对话框
        this.addDialogVisible = false
        //刷新数据列表
        this.getComAdviceList()
        this.$message.success('添加投诉建议成功')
      })
    },
    //监听搜索输入框
    clearData() {
      if (this.queryInfo.query == '') {
        delete this.queryInfo.condition
      }
    },
    filterTag(value, row) {
      return row.state === value;
    },
    // 展示编辑投诉建议的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.post("ComplaintinfoAction/getObjectById", { id })
      if (!res.success)
        return this.$message.error('查询投诉建议失败')
      this.editForm = res.rows[0]
      this.editDialogVisible = !this.editDialogVisible
    },
    //点击按钮
    edit() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post("ComplaintinfoAction/updateNoNull", this.editForm)
        if (!res.success) return this.$message.error('修改投诉建议信息失败')
        //关闭对话框
        this.editDialogVisible = false
        //刷新数据列表
        this.getComAdviceList()
        this.$message.success('修改投诉建议信息成功')
      })
    },
    // 根据id删除投诉建议
    async removeUserById(ids) {
      // 先弹框询问用户是否确定要删除
      const confirmResult = await this.$confirm('此操作将永久删除该投诉建议记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      // 如果点击取消返回的是字符串cancel
      // 如果点击确认返回的是字符串confirm
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.post("ComplaintinfoAction/deleteByIds", { ids })
      console.log(res);
      if (!res.success) {
        return this.$message.error('删除投诉建议失败')
      }
      this.$message.error('删除投诉建议成功')
      // 刷新列表
      this.getComAdviceList()
    },
    // 监听修改投诉建议对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 监听pagesize改变的事件
    handleSizeChange(newPageSize) {
      // console.log(newPageSize)
      this.queryInfo.pageSize = newPageSize
      // PageSize改变重新拿到投诉建议列表
      this.getComAdviceList()
    },
    // 监听当前页码改变的事件
    handleCurrentChange(newPageNum) {
      // console.log(newPageNum)
      this.queryInfo.pageNum = newPageNum
      this.getComAdviceList()
    },
    addDialogReset() {
      // 拿到表单的引用进行重置
      this.$refs.addFormRef.resetFields()
    },
    //批量删除
    async removeUserByIds() {
      const rows = this.$refs.tableDataRef.selection;
      if (rows.length === 0) {
        this.$message.warning('请选择需要操作的数据')
        return
      }
      else {
        // 先弹框询问用户是否确定要删除
        const confirmResult = await this.$confirm('此操作将永久删除该投诉建议, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => {
          return err
        })
        if (confirmResult !== 'confirm') {
          return this.$message.info('取消了删除')
        }
        const { data: res } = await this.$http.post("ComplaintinfoAction/deleteByIds", this.idsArray)
        console.log(res);
        if (!res.success) {
          return this.$message.error('删除投诉建议失败')
        }
        this.$message.success('删除投诉建议成功')
        //此时全选框还是选中状态，批量删除后需清除选中状态
        this.$refs.tableDataRef.clearSelection();
        // 刷新列表
        this.getComAdviceList()
      }

    },
    //当多选框选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.idsArray.ids = [] //每次点击需清空原本数组的内容
      this.multipleSelection.map(item => { //遍历数组，把id存进自定义的数组里
        this.idsArray.ids.push(item.id)
      })
      this.idsArray.ids = this.idsArray.ids.join(',')
      // console.log(this.idsArray);

    },
    //导出Excel表
    handleDownload() {
      window.open(axios.defaults.baseURL + '/ComplaintinfoAction/exportDataToExcel?token=' + window.sessionStorage.getItem('token'))
    },
    // 全选或取消全选实现
    filterFunHandle(type, currentItem, index) {
      if (type === 'allchecked') { // 全选
        if (this.colSelect.length === 0) {
          this.colData.forEach((result) => {
            this.colSelect.push(result.title)
          })
          this.colOptions = this.colSelect // 复选框置为复选所有值，全部选择

        } else {
          this.colOptions = this.colSelect // 复选框置为复选所有值，全部选择

        }
      } else if (type === 'cancel') { // 取消全选
        this.colOptions = [] // 复选框置为空，全部不选择

      }
    },
  }
}
</script>
<style lang="less" scoped>
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 202px;
}
</style>